package com.example.weight.greenSeasons.waterDeal;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.arrayAdapter.Item;
import com.example.weight.arrayAdapter.ItemAdapter;
import com.example.weight.config.Config;
import com.example.weight.greenSeasons.researchDevelopment.IncomingScene;
import com.example.weight.householdWaste.YijingStationResourceActivity;
import com.example.weight.navigation.SijiqingFlocculationNavActivity;
import com.example.weight.util.Utility;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import android.app.Activity;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class RepairTable extends AppCompatActivity implements View.OnClickListener{
    private TitleBar titleBar;
    private String name, factory;
    private TextView equipment_name;
    private TextView start_time;
    private TextView end_time;
//    private TextView repair_personInCharge;
    private TextView repair_process;
    DateFormat format= DateFormat.getDateTimeInstance();
    Calendar calendar= Calendar.getInstance(Locale.CHINA);

    private SharedPreferences preferences;
    private ItemAdapter personAdapter;
    private List<String> personList;
    private EditText repair_personInCharge;
    private PopupWindow personPopupWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_repair_table);
        titleBar=findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {

            @Override
            public void onLeftClick(View v) {
                RepairTable.this.finish();
            }
            @Override
            public void onTitleClick(View v) { }
            @Override
            public void onRightClick(View v) { }
        });

        /**
         * 两个个时间
         */
        start_time = (TextView) findViewById(R.id.start_time);
        start_time.setOnClickListener(this);
        end_time = (TextView) findViewById(R.id.end_time);
        end_time.setOnClickListener(this);

        equipment_name = (TextView) findViewById(R.id.equipmemt_name);
        repair_process = (TextView) findViewById(R.id.repair_process);


        // 设置输入记录缓存
        preferences = getSharedPreferences("activity_repair_table", Context.MODE_PRIVATE);
        repair_personInCharge = findViewById(R.id.repair_personInCharge);
        personList = new ArrayList<>(preferences.getStringSet("personList", new HashSet<>()));
        List<Item> personItemList = new ArrayList<>();
        // Item类型list初始化
        for (String itemName : personList) {
            personItemList.add(new Item(itemName, R.drawable.ic_clear));
        }
        // 创建ListView
        personAdapter = new ItemAdapter(this, R.layout.adapter_item, personItemList);
        ListView personListView = new ListView(this);
        personListView.setAdapter(personAdapter);
        personListView.setOnItemClickListener((parent, view, position, id) -> {
            // 若有进行删除操作，更新nameList，否则nameList序号对不上
            if (personAdapter.getDeletePos() >= 0) {
                List<Item> tempItemList = personAdapter.getList();
                personList.clear();
                for (Item item : tempItemList) {
                    personList.add(item.getName());
                }
            }
            // 根据所选设置输入框文本
            String result = personList.get(position);
            repair_personInCharge.setText(result);
            personPopupWindow.dismiss();
            hideInput();
        });

        // 获取屏幕的宽度并设置popupwindow的宽度为width,这里是根据布局控件所占的权重
        WindowManager wManager = (WindowManager) getSystemService(this.WINDOW_SERVICE);
        int width = wManager.getDefaultDisplay().getWidth() * 3 / 5;
        int height = wManager.getDefaultDisplay().getHeight() / 8;
        // 参数为 1.View 2.宽度 3.高度
        personPopupWindow = new PopupWindow(personListView ,width,height);
        // 设置点击外部区域可以取消popupWindow
        personPopupWindow.setOutsideTouchable(true);

        repair_personInCharge.setOnFocusChangeListener((v, hasFocus) -> {
            // 设置popupWindow显示,并且告诉它显示在那个View下面
            if (hasFocus) {
                // 若聚焦到该输入框，显示下拉列表
                personPopupWindow.showAsDropDown(repair_personInCharge);
            }
        });



        //获取当天最新一条数据
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/sjq/overhaul/findForm" + "?factory=" + factory;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            JSONObject data;
                            if(jsonObject.get("data")!=null && !jsonObject.get("data").toString().equals("null")){
                                data = jsonObject.getJSONObject("data");
                                if (!data.isNull("id")) {
                                    equipment_name.setText(data.getString("equipmentName"));
                                    start_time.setText(data.getString("startTime"));
                                    end_time.setText(data.getString("endTime"));
                                    repair_personInCharge.setText(data.getString("personIncharge"));
                                    repair_process.setText(data.getString("process"));
                                    Toast.makeText(RepairTable.this,
                                            "今日已填写此表", Toast.LENGTH_SHORT).show();
                                }
                            }else {
                                start_time.setHint("00:00");
                                end_time.setHint("00:00");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(RepairTable.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);
    }


    /**
     * 提交内容并设置输入缓存
     * @param view
     */
    public void save(View view) {
        if(equipment_name.getText().toString().equals("")) {
            Toast.makeText(this, "请填写设备名称", Toast.LENGTH_SHORT).show();
            return;
        }
        if(start_time.getText().toString().equals("")) {
            Toast.makeText(this, "请填写大修开始时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (end_time.getText().toString().equals("")) {
            Toast.makeText(this, "请填写大修结束时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (repair_personInCharge.getText().toString().equals("")) {
            Toast.makeText(this, "请填写大修负责人", Toast.LENGTH_SHORT).show();
            return;
        }
        if (repair_process.getText().toString().equals("")) {
            Toast.makeText(this, "请填写大修过程记录", Toast.LENGTH_SHORT).show();
            return;
        }
        new AlertDialog.Builder(this)
                .setTitle("确定保存吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->
                        Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
                .setPositiveButton("确定", (dialog, which) -> {
                    //输入缓存
                    SharedPreferences.Editor editor = preferences.edit();
                    // 若有进行删除操作，更新personList
                    List<Item> tempPersonList = personAdapter.getList();
                    if (tempPersonList.size() != personList.size()) {
                        personList.clear();
                        for (Item item : tempPersonList) {
                            personList.add(item.getName());
                        }
                    }
                    // 判断该输入框内容是否已存在，不存在则加入
                    String currentBatch = repair_personInCharge.getText().toString();
                    if (!currentBatch.equals("") && !personList.contains(currentBatch)) {
                        personList.add(currentBatch);
                    }


                    editor.putStringSet("personList", new HashSet<>(personList));
                    editor.apply();

                    //提交请求
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/sjq/overhaul/addForm";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    //Toast.makeText(RepairTable.this, "保存成功", Toast.LENGTH_SHORT).show();
                                    Log.d("LB", response);
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");
                                        if (code.startsWith("2"))
                                            Toast.makeText(RepairTable.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        else
                                            Toast.makeText(RepairTable.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(RepairTable.this, "保存失败", Toast.LENGTH_SHORT).show();
                            Log.d("LB", error.toString());
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map=new HashMap<>();
                            map.put("equipment_name",  equipment_name.getText().toString());
                            map.put("start_time", start_time.getText().toString());
                            map.put("end_time", end_time.getText().toString());
                            map.put("person_incharge", repair_personInCharge.getText().toString());
                            map.put("process", repair_process.getText().toString());
                            map.put("recorder",name);
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }




    /**
     * 隐藏键盘
     */
    protected void hideInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        View v = getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }

    /**
     * 时间选择
     * @param activity
     * @param themeResId
     * @param tv
     * @param calendar
     */
    public static void showTimePickerDialog(Activity activity, int themeResId, final TextView tv, Calendar calendar) {
        // Calendar c = Calendar.getInstance();
        // 创建一个TimePickerDialog实例，并把它显示出来
        // 解释一哈，Activity是context的子类
        new TimePickerDialog( activity,themeResId,
                // 绑定监听器
                new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
//                        tv.setText(hourOfDay + ":" + minute);
                        tv.setText(String.format("%02d", hourOfDay) + ":" + String.format("%02d", minute));
                    }
                }
                // 设置初始时间
                , calendar.get(Calendar.AM_PM)
                , calendar.get(Calendar.MINUTE)
                // true表示采用24小时制
                ,true).show();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.start_time:
                showTimePickerDialog(this,  2, start_time, calendar);
                break;
            case R.id.end_time:
                showTimePickerDialog(this,  2, end_time, calendar);;
                break;
            default:
                break;
        }
    }

}